<template>
  <div class="container">
    <div class="panel">
      <div style="line-height: 40px;">你好：{{userInfo.username}}</div>
      <el-form :model="userForm" :rules="rules" ref="userForm" label-width="100px" status-icon>
        <el-form-item label="旧密码" prop="oldPwd">
          <el-input v-model="userForm.oldPwd"></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPwd">
          <el-input v-model="userForm.newPwd" type="password" autocomplete="off"></el-input>
        </el-form-item>      
        <el-form-item label="确认密码" prop="checkPwd">
          <el-input v-model="userForm.checkPwd" type="password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('userForm')">提交</el-button>
          <el-button @click="resetForm('userForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
  
</template>

<script>
import request from '@/util/request.js'
export default {
    name: 'UserCenter',
    data() {
      // 两次密码验证规则
      var validatePass2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.userForm.newPwd) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
      return {
        userInfo: {
          id: '',
          username: '',
          avatar: ''
        },
        userForm: {
          oldPwd: '',
          newPwd: '',
          checkPwd: ''
        },
        rules: {
          oldPwd: [
            { required: true, message: '请输入旧密码', trigger: 'blur' }
          ],
          newPwd: [
            { required: true, message: '请输入新密码', trigger: 'blur' },
            { min: 3, max: 12, message: '长度在 3 到 12 个字符', trigger: 'blur' }
          ],
          checkPwd: [
            { validator: validatePass2, trigger: 'blur' }
          ]
        }
      }
    },
    created() {
      this.getUserInfo()
    },
    methods: {
      getUserInfo() {
        request.get('/user/info').then(res=>{
          this.userInfo = res.data
        })
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            alert('submit!');
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      }
    }
}
</script>

<style scoped>
  .container {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .panel {
    width: 360px;
  }
</style>